<template>
  <div style="margin: 10px;height: 100vh"  v-loading="spinning">
    <el-row>
      <el-col :span="24">
        <el-row :gutter="24">
          <el-col :span="15">
            <el-button type="primary" @click="departmentSaveOrUpdateShow('')" plain>
              新增
            </el-button>

            <el-button type="success" @click="departmentSaveOrUpdateShow(handleSelectionChangeData[0].id)" :icon="Edit" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1"  plain>
              修改
            </el-button>

            <el-button type="primary" @click="dialogVisible=true;sysMsg='确定要启用【'+handleSelectionChangeData[0].departmentName+'】本部门';sysOperateType='updatyeDepartmentState';sysOperateId=handleSelectionChangeData[0].id;":icon="Open" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1||(handleSelectionChangeData.length==1&&handleSelectionChangeData[0].departmentState!='STOP')"  plain>
              启用
            </el-button>

            <el-button type="warning" @click="dialogVisible=true;sysMsg='确定要停用【'+handleSelectionChangeData[0].departmentName+'】本部门及子部门';sysOperateType='updatyeDepartmentState';sysOperateId=handleSelectionChangeData[0].id;" :icon="TurnOff" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1||(handleSelectionChangeData.length==1&&handleSelectionChangeData[0].departmentState!='NORMAL')"  plain>
              停用
            </el-button>

          </el-col>
          <el-col :span="9">

            <div class="ml-4" style="position: relative;
    float: right;">
              <el-tooltip
                  effect="dark"
                  content="刷新"
              >
                <el-button circle @click="getTree">
                  <el-icon :class="{'is-loading':spinning}">
                    <Refresh/>
                  </el-icon>
                </el-button>
              </el-tooltip>
             </div>

          </el-col>
        </el-row>
      </el-col>
      <el-col :span="24">
        <el-container>
          <!--        数据-->
          <el-main>
        <el-table
            :data="tableData"
            style="width: auto" header-row-class-name="etable" height="90vh"
            row-key="id"
            border
            :highlight-current="true"
            :default-expand-all="true"
            :tree-props="{ children: 'childDepartmentList'}"
            @selection-change="handleSelectionChange"
            stripe
        >
          <el-table-column type="selection"  width="55" />
          <el-table-column prop="departmentName" label="部门名称"/>
          <el-table-column label="状态" min-width="20">
            <template #default="scope">
              <el-tag :type="scope.row.departmentStateTagEnumBean.style.type" round>
                {{ scope.row.departmentStateTagEnumBean.msg }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="departmentSort" label="排序"/>
          <el-table-column fixed="right" label="操作">


            <template #default="scope">

              <el-button
                  size="small"
                  style="margin-right: 2px"
                  v-if="scope.row.pid!='0'"
                  link type="success"
                  @click=" departmentSaveOrUpdateShow(scope.row.id)"
                  :icon="Edit"
              >
                修改
              </el-button>





              <el-button link size="small" type="primary"v-if="scope.row.departmentState=='STOP'&&scope.row.pid!='0'" @click="dialogVisible=true;sysMsg='确定要启用【'+scope.row.departmentName+'】本部门';sysOperateType='updatyeDepartmentState';sysOperateId=scope.row.id;":icon="Open"  plain>
                启用
              </el-button>

              <el-button link size="small" type="warning"v-if="scope.row.departmentState=='NORMAL'&&scope.row.pid!='0'" @click="dialogVisible=true;sysMsg='确定要停用【'+scope.row.departmentName+'】本部门及子部门';sysOperateType='updatyeDepartmentState';sysOperateId=scope.row.id;" :icon="TurnOff"  plain>
                停用
              </el-button>



            </template>


          </el-table-column>

        </el-table>

        </el-main>
        </el-container>
      </el-col>

    </el-row>





  <el-dialog v-model="saveOrUpdateVisible" :title="saveUpdateTitle" width="800px">
    <el-form :model="DepartmentSaveOrUpdateParam" label-width="auto" style="max-width: 800px"
             ref="departmentSaveOrUpdateRef"
             :rules="departmentSaveOrUpdateRules"
    >
      <el-form-item label="上级属部门" prop="pid">
        <el-tree-select
            v-model="DepartmentSaveOrUpdateParam.pid"
            :data="treeData"
            check-strictly
            :render-after-expand="false"
            node-key="id"
            style="width: 100%;background-color: #ccccff"
            :props="replaceFields"

        />


      </el-form-item>


      <el-form-item label="部门名称" prop="departmentName">
        <el-input v-model="DepartmentSaveOrUpdateParam.departmentName" clearable/>
      </el-form-item>
      <el-form-item label="排序" prop="departmentSort">
        <el-input-number v-model="DepartmentSaveOrUpdateParam.departmentSort" :min="1" :max="99"/>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveSubmit(departmentSaveOrUpdateRef)" v-if="updateDepartmentId==''" :loading="spinning">添加
        </el-button>
        <el-button type="primary" @click="updateSubmit(departmentSaveOrUpdateRef)" v-if="updateDepartmentId!=''" :loading="spinning">修改
        </el-button>
        <el-button @click="saveOrUpdateVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>

    <el-dialog
        v-model="dialogVisible"
        title="系统提示"
        width="500"
        align-center
    >
      <span>{{sysMsg}}</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sysOperate()" :loading="spinning">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref, toRaw, reactive, type Ref, type UnwrapRef} from 'vue'

import request from "@/api/request";
import {DepartmentFromInfo, DepartmentSaveOrUpdateParam} from "@/views/sys/department/departmentInfo";

import {type FormInstance, type ElDialog, type FormRules, ElMessage} from "element-plus";
import {Edit, Open, TurnOff} from "@element-plus/icons-vue";

//列表默认折叠
let defaultExpandAll = ref(false);
let spinning = ref<boolean>(false);
const showQuery = ref(false);

let handleSelectionChangeData=ref();

let dialogVisible = ref<boolean>(false);
let sysMsg = ref("");
let sysOperateType=ref("");
let sysOperateId=ref("");

function sysOperate(){
  spinning.value = true;
  console.log(2222222222222222)
  if(sysOperateType.value=="updatyeDepartmentState"){
    updatyeDepartmentState(sysOperateId.value)

  }


}




//是否展示过滤列按钮
let isColumnsShow = defineModel('isColumnsShow')
//左侧树数据
// let treeData = ref<TreeProps['treeData']>([]);
//左侧树数据对应的结构
const replaceFields = {
  children: 'childDepartmentList',
  label: 'departmentName',
  id: 'id',
};

const handleSelectionChange = (val: number) => {
  handleSelectionChangeData.value=val;
}
let treeData = ref([]);
const tableData: Ref<UnwrapRef<any[]>> = ref([]);

let directoryIds = ref([]);

//页面加载
onMounted(() => {

  getTree()

})


//列表加载
function getTree() {
  spinning.value = true;
  request.get('/sysDepartment/departmentTree').then((res: any) => {
    spinning.value = false;
    if (res.code == '10000') {
      treeData.value = res.data;
      tableData.value = res.data;
    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    spinning.value = false;
  })
}


//修改的用户id
let updateDepartmentId = ref<string>("");
//添加修改是否可见弹窗
let saveOrUpdateVisible = ref<boolean>(false)
//弹窗标题
let saveUpdateTitle = ref<string>("添加部门");

function departmentSaveOrUpdateShow(id: string) {

  if (id == null || id == '') {
    DepartmentFromInfo(null)
    updateDepartmentId.value = "";
    saveUpdateTitle = ref("添加部门信息");
    saveOrUpdateVisible.value = true;

  } else {
    spinning.value = true;
    request.get('/sysDepartment/' + id).then((res: any) => {
      spinning.value = false;
      if (res.code == '10000') {
        updateDepartmentId.value = id;
        saveUpdateTitle.value = "修改部门信息";

        DepartmentFromInfo(res.data);

        saveOrUpdateVisible.value = true;
      } else {
        ElMessage.error(res.errorMessage);
      }
    }).catch((error) => {
      spinning.value = false;
    })
  }
}

const departmentSaveOrUpdateRef = ref<FormInstance>()
//添加修改验证
const departmentSaveOrUpdateRules = reactive<FormRules<DepartmentSaveOrUpdateParam>>({
  pid: [
    {required: true, message: '请选择上级部门', trigger: 'blur'}
  ],
  departmentName: [
    {required: true, message: '请填写部门名称', trigger: 'blur'}
  ],
  departmentSort: [
    {required: true, message: '请填写部门排序', trigger: 'blur'}
  ],
});

const saveSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {

      request.post('/sysDepartment/', DepartmentSaveOrUpdateParam).then((res: any) => {

        saveOrUpdateVisible.value = false;
        if (res.code == '10000') {
          ElMessage.success("添加成功");

          saveOrUpdateVisible.value = false;
          getTree();
        } else {
          ElMessage.error(res.errorMessage);
        }
      }).catch((error) => {
        ElMessage.error(error)
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}

//更新用户信息
const updateSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {

      request.put('/sysDepartment/' + updateDepartmentId.value, DepartmentSaveOrUpdateParam).then((res: any) => {
        if (res.code == '10000') {
          ElMessage.success("修改成功");

          saveOrUpdateVisible.value = false;
          getTree();
        } else {
          ElMessage.error(res.errorMessage);
        }
      }).catch((error) => {
        ElMessage.error(error)
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}


function updatyeDepartmentState(id: string) {

  request.put('/sysDepartment/updatyeDepartmentState/' + id).then((res: any) => {
    dialogVisible.value = false
    spinning.value = false;
    // queryFormInlineSubmit.value=null;
    if (res.code == '10000') {
      ElMessage.success("变更成功");
      getTree();
    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    spinning.value = false;
  })

}


//删除取消
const updateCancel = (e: MouseEvent) => {
};


</script>
